package com.crazy.writer.book;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.crazy.writer.book.util.FileUtil;

public class BookStorage {

    private static String root;

    private static File book;

    private static File dic;

    private static Map<Integer, Character> mi2ming = new HashMap<Integer, Character>();

    private static Map<Character, Integer> ming2mi = new HashMap<Character, Integer>();

    private static List<String> needUpdateDic = new ArrayList<String>();

    public static String save(String content) {
	FileUtil.appendToFile(content, book);
	content = jiami(content);
	saveDic(needUpdateDic);
	return content;
    }

    private static void saveDic(List<String> needUpdateDic2) {
	if(!needUpdateDic2.isEmpty()) {
	    FileUtil.appendToFileByLine(needUpdateDic2, dic);
	}
    }

    private static String jiami(String content) {
	needUpdateDic.clear();
	StringBuilder jiami = new StringBuilder("");
	for (int i = 0; i < content.length(); i++) {
	    char key = content.charAt(i);
	    if (key == ' ' || key == '\r' || key == '\n') {
		jiami.append(key);
	    } else {
		Integer no = null;
		if (ming2mi.get(key) == null) {
		    no = ming2mi.size() + 1;
		    needUpdateDic.add(key + "&&" + no);
		    ming2mi.put(key, no);
		    mi2ming.put(no, key);
		} else {
		    no = ming2mi.get(key);
		}
		jiami.append("(").append(no).append(")");
	    }
	}
	return jiami.toString();
    }

    public static String loadHistory(int hang) {
	List<String> duan = FileUtil.readFileByLine(book);
	if (duan.size() < hang) {
	    hang = duan.size();
	}
	StringBuilder sb = new StringBuilder("");
	for (int i = hang; i > 0; i--) {
	    sb.append(duan.get(duan.size() - i)).append("\r\n");
	}
	return sb.toString();
    }

    public static void loadPath(File file) {
	book = file;
	root = file.getParent();

	initDic();
    }

    private static void initDic() {
	dic = new File(root + File.separator + "dic.txt");
	if (!dic.exists()) {
	    try {
		dic.createNewFile();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	} else {
	    List<String> dics = FileUtil.readFileByLine(dic);

	   for(String d : dics) {
		String[] dm = d.split("\\&\\&");
		Integer mi = Integer.valueOf(dm[1]);
		Character ming = Character.valueOf(dm[0].charAt(0));
		mi2ming.put(mi, ming);
		ming2mi.put(ming, mi);
	   }
	}

    }

}
